package com.novel.crawl.common.controller;

import com.novel.common.entity.Entity;
import com.novel.common.service.BaseService;
import com.novel.crawl.common.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author 奔波儿灞
 * @since 1.0
 */
@CrossOrigin(
        origins = "*",
        allowedHeaders = "*",
        methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE},
        maxAge = 3600
)
public abstract class BaseController<T extends Entity> {

    /**
     * 默认分页中没页显示的数据量
     */
    protected final int DEFAULT_SIZE = 20;

    @Autowired
    private BaseService<T> baseService;

    /**
     * 根据不为空的字段分页查询，第一页page为0
     *
     * @param entity 实体
     * @return Rest<Page < T>>
     */
    @GetMapping
    public Rest<Page<T>> page(T entity, @PageableDefault(size = DEFAULT_SIZE) Pageable pageable) {
        return Rest.ok(baseService.page(entity, pageable));
    }

    /**
     * 查询
     *
     * @param id 主键
     * @return Rest<T>
     */
    @GetMapping("/{id}")
    public Rest<T> show(@PathVariable String id) {
        return Rest.ok(baseService.findById(id));
    }

    /**
     * 添加
     *
     * @param entity 实体
     * @return Rest<T>
     */
    @PostMapping
    public Rest<T> add(@Validated @RequestBody T entity) {
        baseService.add(entity);
        return Rest.ok(entity);
    }

    /**
     * 修改，字段不为空则更新
     *
     * @param entity 实体
     * @return Rest<T>
     */
    @PutMapping
    public Rest<T> modify(@Validated @RequestBody T entity) {
        baseService.modify(entity);
        return Rest.ok(entity);
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return Rest<Void>
     */
    @DeleteMapping("/{id}")
    public Rest<Void> delete(@PathVariable String id) {
        baseService.deleteById(id);
        return Rest.ok();
    }

}
